package cn.li.security.jwt;

import cn.li.security.json.bean.Result;
import cn.li.security.json.handle.BaseJSONHandler;
import cn.li.security.jwt.service.IJwtService;
import cn.li.security.jwt.service.JwtResult;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 登录成功的JSON处理
 */
public class JwtAuthenticationSuccessHandler extends BaseJSONHandler implements AuthenticationSuccessHandler {

    private IJwtService jwtService;
    public static final String LOGIN_SUCCESS_MSG = "LOGIN_SUCCESS";

    public JwtAuthenticationSuccessHandler(IJwtService jwtService, ObjectMapper objectMapper) {
        super(objectMapper);
        this.jwtService = jwtService;
    }

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        UserDetails details = (UserDetails) authentication.getPrincipal();
        JwtResult jwt = jwtService.generator(details);
        Result r = new Result(0, LOGIN_SUCCESS_MSG,jwt);
        this.writeResult(response,r);
    }
}
